<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ETH转账DApp - Sepolia测试网</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        body {
            background: linear-gradient(135deg, #1a202c 0%, #2d3748 100%);
            color: #e2e8f0;
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        .container {
            width: 100%;
            max-width: 800px;
            background: rgba(26, 32, 44, 0.8);
            border-radius: 16px;
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4);
            overflow: hidden;
            padding: 30px;
        }

        header {
            text-align: center;
            margin-bottom: 30px;
        }

        h1 {
            font-size: 2.5rem;
            color: #63b3ed;
            margin-bottom: 10px;
        }

        .description {
            color: #a0aec0;
            font-size: 1.1rem;
            margin-bottom: 20px;
        }

        .status-card {
            background: rgba(45, 55, 72, 0.6);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        .status {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .status-icon {
            font-size: 1.5rem;
        }

        .connected {
            color: #68d391;
        }

        .disconnected {
            color: #fc8181;
        }

        .btn {
            background: #4299e1;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 1rem;
            font-weight: 600;
            transition: all 0.3s ease;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }

        .btn:hover {
            background: #3182ce;
            transform: translateY(-2px);
        }

        .btn:disabled {
            background: #4a5568;
            cursor: not-allowed;
            transform: none;
        }

        .btn-primary {
            background: #ed64a6;
        }

        .btn-primary:hover {
            background: #d53f8c;
        }

        .account-info {
            background: rgba(45, 55, 72, 0.6);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .info-row {
            display: flex;
            margin-bottom: 15px;
        }

        .info-label {
            width: 150px;
            color: #a0aec0;
        }

        .info-value {
            flex: 1;
            word-break: break-all;
        }

        .transfer-form {
            background: rgba(45, 55, 72, 0.6);
            border-radius: 12px;
            padding: 20px;
            margin-bottom: 25px;
        }

        .form-group {
            margin-bottom: 20px;
        }

        label {
            display: block;
            margin-bottom: 8px;
            color: #a0aec0;
        }

        input {
            width: 100%;
            background: rgba(26, 32, 44, 0.7);
            border: 1px solid #4a5568;
            border-radius: 8px;
            color: white;
            padding: 12px 15px;
            font-size: 1rem;
        }

        input:focus {
            outline: none;
            border-color: #4299e1;
        }

        .transaction-result {
            background: rgba(45, 55, 72, 0.6);
            border-radius: 12px;
            padding: 20px;
        }

        .result-title {
            font-size: 1.2rem;
            color: #63b3ed;
            margin-bottom: 15px;
        }

        .transaction-hash {
            word-break: break-all;
            font-family: monospace;
            background: rgba(0, 0, 0, 0.3);
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 15px;
        }

        .footer {
            text-align: center;
            margin-top: 30px;
            color: #718096;
            font-size: 0.9rem;
        }

        .network-alert {
            background: rgba(254, 178, 178, 0.2);
            border: 1px solid #fc8181;
            border-radius: 8px;
            padding: 15px;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        @media (max-width: 600px) {
            .container {
                padding: 15px;
            }

            h1 {
                font-size: 2rem;
            }

            .info-row {
                flex-direction: column;
            }

            .info-label {
                width: 100%;
                margin-bottom: 5px;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <header>
            <h1><i class="fab fa-ethereum"></i> ETH转账DApp</h1>
            <p class="description">连接MetaMask钱包，安全地转账ETH（Sepolia测试网）</p>
        </header>

        <div class="network-alert" id="networkAlert" style="display: none;">
            <i class="fas fa-exclamation-circle" style="color: #fc8181;"></i>
            <div>请切换到Sepolia测试网络以使用此DApp</div>
        </div>

        <div class="status-card">
            <div class="status">
                <div class="status-icon disconnected" id="statusIcon">
                    <i class="fas fa-times-circle"></i>
                </div>
                <div>
                    <div>钱包状态</div>
                    <div id="statusText">未连接</div>
                </div>
            </div>
            <button id="connectButton" class="btn">
                <i class="fas fa-plug"></i> 连接钱包
            </button>
        </div>

        <div class="account-info" id="accountInfo" style="display: none;">
            <div class="info-row">
                <div class="info-label">账户地址:</div>
                <div class="info-value" id="accountAddress"></div>
            </div>
            <div class="info-row">
                <div class="info-label">ETH 余额:</div>
                <div class="info-value" id="ethBalance"></div>
            </div>
            <div class="info-row">
                <div class="info-label">网络:</div>
                <div class="info-value" id="network"></div>
            </div>
        </div>

        <div class="transfer-form">
            <h3><i class="fas fa-exchange-alt"></i> ETH转账</h3>
            <div class="form-group">
                <label for="recipientAddress">接收地址:</label>
                <input type="text" id="recipientAddress" placeholder="输入接收地址 (0x...)">
            </div>
            <div class="form-group">
                <label for="ethAmount">ETH数量:</label>
                <input type="number" id="ethAmount" placeholder="输入ETH数量" step="0.001">
            </div>
            <button id="transferButton" class="btn btn-primary" disabled>
                <i class="fas fa-paper-plane"></i> 签名并转账
            </button>
        </div>

        <div class="transaction-result" id="transactionResult" style="display: none;">
            <div class="result-title"><i class="fas fa-check-circle"></i> 交易已提交</div>
            <div class="transaction-hash" id="transactionHash"></div>
            <p>交易正在处理中，请稍候...</p>
        </div>

        <div class="footer">
            <p>请确保您已安装 <a href="https://metamask.io/" target="_blank" style="color: #63b3ed;">MetaMask</a> 钱包</p>
            <p>仅支持Sepolia测试网络</p>
        </div>
    </div>

    <!-- 引入Web3.js库 -->
    <script src="https://cdn.jsdelivr.net/npm/web3@1.8.0/dist/web3.min.js"></script>

    <script>
        // 全局变量
        let web3;
        let userAccount;
        let chainId;

        // 智能合约ABI和地址 (示例合约，实际使用时需要替换)
        const CONTRACT_ABI = [
            {
                "inputs": [
                    { "internalType": "address", "name": "to", "type": "address" },
                    { "internalType": "uint256", "name": "amount", "type": "uint256" },
                    { "internalType": "bytes", "name": "signature", "type": "bytes" }
                ],
                "name": "transferWithSignature",
                "outputs": [{ "internalType": "bool", "name": "", "type": "bool" }],
                "stateMutability": "payable",
                "type": "function"
            },
            {
                "inputs": [],
                "name": "getContractBalance",
                "outputs": [{ "internalType": "uint256", "name": "", "type": "uint256" }],
                "stateMutability": "view",
                "type": "function"
            }
        ];

        // 请替换为您部署的合约地址
        const CONTRACT_ADDRESS = "0xC60c83E22308175A1F68FD00bAFD29C5e59eA45F";

        // Sepolia测试网络链ID
        const SEPOLIA_CHAIN_ID = "0xaa36a7"; // 11155111的十六进制

        // DOM元素
        const connectButton = document.getElementById('connectButton');
        const statusIcon = document.getElementById('statusIcon');
        const statusText = document.getElementById('statusText');
        const accountInfo = document.getElementById('accountInfo');
        const accountAddress = document.getElementById('accountAddress');
        const ethBalance = document.getElementById('ethBalance');
        const network = document.getElementById('network');
        const transferButton = document.getElementById('transferButton');
        const recipientAddressInput = document.getElementById('recipientAddress');
        const ethAmountInput = document.getElementById('ethAmount');
        const transactionResult = document.getElementById('transactionResult');
        const transactionHash = document.getElementById('transactionHash');
        const networkAlert = document.getElementById('networkAlert');

        // 初始化 - 检查是否已安装MetaMask
        window.addEventListener('load', async () => {
            if (typeof window.ethereum !== 'undefined') {
                console.log('MetaMask 已安装');
                web3 = new Web3(window.ethereum);

                // 检查是否已经连接
                try {
                    const accounts = await web3.eth.getAccounts();
                    if (accounts.length > 0) {
                        await connectWallet();
                    }
                } catch (error) {
                    console.error("获取账户失败:", error);
                }

                // 检查当前网络
                checkNetwork();
            } else {
                alert('请安装MetaMask钱包!');
                connectButton.disabled = true;
            }
        });

        // 连接钱包
        connectButton.addEventListener('click', connectWallet);

        async function connectWallet() {
            try {
                // 请求账户连接
                const accounts = await window.ethereum.request({
                    method: 'eth_requestAccounts'
                });

                userAccount = accounts[0];

                // 获取网络ID
                chainId = await web3.eth.getChainId();

                // 检查网络
                checkNetwork();

                // 更新UI
                updateWalletStatus(true);
                updateAccountInfo();

                // 启用转账按钮
                if (isSepoliaNetwork()) {
                    transferButton.disabled = false;
                }

            } catch (error) {
                console.error("连接钱包失败:", error);
                alert('连接钱包失败: ' + error.message);
            }
        }

        // 检查当前网络
        function checkNetwork() {
            if (isSepoliaNetwork()) {
                networkAlert.style.display = 'none';
                if (userAccount) {
                    transferButton.disabled = false;
                }
            } else {
                networkAlert.style.display = 'flex';
                transferButton.disabled = true;
            }
        }

        // 检查是否是Sepolia网络
        function isSepoliaNetwork() {
            return chainId === parseInt(SEPOLIA_CHAIN_ID, 16);
        }

        // 切换到Sepolia网络
        async function switchToSepolia() {
            try {
                await window.ethereum.request({
                    method: 'wallet_switchEthereumChain',
                    params: [{ chainId: SEPOLIA_CHAIN_ID }],
                });
                // 重新加载页面
                window.location.reload();
            } catch (error) {
                // 如果网络未添加，尝试添加它
                if (error.code === 4902) {
                    try {
                        await window.ethereum.request({
                            method: 'wallet_addEthereumChain',
                            params: [
                                {
                                    chainId: SEPOLIA_CHAIN_ID,
                                    chainName: 'Sepolia Test Network',
                                    rpcUrls: ['https://sepolia.infura.io/v3/'],
                                    nativeCurrency: {
                                        name: 'Sepolia Ether',
                                        symbol: 'ETH',
                                        decimals: 18
                                    },
                                    blockExplorerUrls: ['https://sepolia.etherscan.io']
                                }
                            ]
                        });
                    } catch (addError) {
                        console.error("添加Sepolia网络失败:", addError);
                    }
                }
                console.error("切换网络失败:", error);
            }
        }

        // 更新钱包状态UI
        function updateWalletStatus(connected) {
            if (connected) {
                statusIcon.innerHTML = '<i class="fas fa-check-circle"></i>';
                statusIcon.classList.remove('disconnected');
                statusIcon.classList.add('connected');
                statusText.textContent = '已连接';
                connectButton.textContent = '断开连接';
                accountInfo.style.display = 'block';
            } else {
                statusIcon.innerHTML = '<i class="fas fa-times-circle"></i>';
                statusIcon.classList.remove('connected');
                statusIcon.classList.add('disconnected');
                statusText.textContent = '未连接';
                connectButton.textContent = '连接钱包';
                accountInfo.style.display = 'none';
                transactionResult.style.display = 'none';
                transferButton.disabled = true;
            }
        }

        // 更新账户信息
        async function updateAccountInfo() {
            if (!userAccount) return;

            accountAddress.textContent = userAccount;

            // 获取余额
            try {
                const balance = await web3.eth.getBalance(userAccount);
                ethBalance.textContent = web3.utils.fromWei(balance, 'ether') + ' ETH';
            } catch (error) {
                console.error("获取ETH余额失败:", error);
                ethBalance.textContent = '获取失败';
            }

            // 获取网络名称
            network.textContent = getNetworkName(chainId);
        }

        // 根据chainId获取网络名称
        function getNetworkName(chainId) {
            switch (chainId) {
                case 1: return '以太坊主网';
                case 5: return 'Goerli测试网';
                case 11155111: return 'Sepolia测试网';
                default: return `未知网络 (${chainId})`;
            }
        }

        // 转账交易
        transferButton.addEventListener('click', async function () {
            const recipient = recipientAddressInput.value;
            const amount = ethAmountInput.value;

            // 验证输入
            if (!web3.utils.isAddress(recipient)) {
                alert('请输入有效的接收地址');
                return;
            }

            if (amount <= 0) {
                alert('请输入有效的ETH数量');
                return;
            }

            try {
                // 创建合约实例
                const contract = new web3.eth.Contract(CONTRACT_ABI, CONTRACT_ADDRESS);

                // 将ETH数量转换为Wei
                const amountInWei = web3.utils.toWei(amount, 'ether');

                // 创建消息哈希
                const message = web3.utils.soliditySha3(
                    { t: 'address', v: recipient },
                    { t: 'uint256', v: amountInWei },
                    { t: 'address', v: CONTRACT_ADDRESS },
                    { t: 'uint256', v: chainId }
                );

                // 请求用户签名
                const signature = await web3.eth.personal.sign(
                    message,
                    userAccount,
                    ""
                );

                // 调用合约的transferWithSignature方法
                const transaction = await contract.methods
                    .transferWithSignature(recipient, amountInWei, signature)
                    .send({
                        from: userAccount,
                        value: amountInWei // 发送ETH到合约
                    });

                // 显示交易结果
                transactionHash.textContent = transaction.transactionHash;
                transactionResult.style.display = 'block';

                // 添加查看交易的链接
                const explorerLink = document.createElement('a');
                explorerLink.href = `https://sepolia.etherscan.io/tx/${transaction.transactionHash}`;
                explorerLink.target = '_blank';
                explorerLink.textContent = '在区块浏览器中查看';
                explorerLink.style.color = '#63b3ed';
                explorerLink.style.marginTop = '15px';
                explorerLink.style.display = 'block';
                transactionResult.appendChild(explorerLink);

                // 更新余额
                await updateAccountInfo();

            } catch (error) {
                console.error("转账失败:", error);
                alert('转账失败: ' + error.message);
            }
        });

        // 监听账户变化
        window.ethereum.on('accountsChanged', function (accounts) {
            if (accounts.length === 0) {
                // 用户断开连接
                userAccount = null;
                updateWalletStatus(false);
            } else if (accounts[0] !== userAccount) {
                // 切换账户
                userAccount = accounts[0];
                updateAccountInfo();
            }
        });

        // 监听网络变化
        window.ethereum.on('chainChanged', function (newChainId) {
            chainId = parseInt(newChainId, 16);
            checkNetwork();
            updateAccountInfo();
        });

        // 添加网络切换按钮事件监听
        networkAlert.addEventListener('click', switchToSepolia);
    </script>
</body>

</html>